<template>
  <div class="course-management">
    <!-- 查询区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="课程ID">
            <el-input v-model="filterForm.courseId" placeholder="请输入课程ID" @keyup.enter="queryCourseDetail"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item style="justify-content: right;">
            <el-button type="primary" @click="queryCourseDetail">查询</el-button>
            <el-button type="default" @click="resetFilter">重置</el-button>
            <el-button type="success" @click="addDialogVisible=true">添加课程</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <!-- 课程详情对话框 -->
    <el-dialog v-model="queryDialogVisible" title="课程信息查询结果" width="50%" @close="handleQueryDialogClose">
      <el-form :model="queryCourseInfo" label-width="120px">
        <el-form-item label="课程ID">
          <el-input v-model="queryCourseInfo.courseId" disabled></el-input>
        </el-form-item>
        <el-form-item label="课程名称">
          <el-input v-model="queryCourseInfo.courseName" disabled></el-input>
        </el-form-item>
        <el-form-item label="课程所属院系">
          <el-input v-model="queryCourseInfo.department" disabled></el-input>
        </el-form-item>
        <el-form-item label="课程学分">
          <el-input v-model="queryCourseInfo.courseCredits" disabled></el-input>
        </el-form-item>
        <el-form-item label="课程描述">
          <el-input v-model="queryCourseInfo.courseDescription" disabled></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 课程列表 -->
    <el-card class="course-list-card">
      <div class="table-container">
        <el-table :data="courseList" stripe border @row-dblclick="handleRowClick" style="width: 100%;" max-height="500px">
          <el-table-column prop="courseId" label="课程ID"></el-table-column>
          <el-table-column prop="courseName" label="课程名称"></el-table-column>
          <el-table-column prop="department" label="课程所属院系"></el-table-column>
          <el-table-column prop="courseCredits" label="课程学分"></el-table-column>
          <el-table-column prop="courseDescription" label="课程描述"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <el-pagination
          class="pagination"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加课程对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加课程" width="50%" @close="handleAddDialogClose">
      <el-form :model="addForm" ref="addFormRef" label-width="120px" :rules="addFormRules">
        <el-form-item label="课程ID" prop="courseId">
          <el-input v-model="addForm.courseId"></el-input>
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="addForm.courseName"></el-input>
        </el-form-item>
        <el-form-item label="课程所属院系" prop="department">
          <el-input v-model="addForm.department"></el-input>
        </el-form-item>
        <el-form-item label="课程学分" prop="courseCredits">
          <el-input-number v-model="addForm.courseCredits" :min="0" step="0.5"></el-input-number>
        </el-form-item>
        <el-form-item label="课程描述" prop="courseDescription">
          <el-input v-model="addForm.courseDescription"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑课程对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑课程" width="50%" @close="handleEditDialogClose">
      <el-form :model="editForm" ref="editFormRef" label-width="120px" :rules="editFormRules">
        <el-form-item label="课程ID" prop="courseId">
          <el-input v-model="editForm.courseId" disabled></el-input>
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="editForm.courseName"></el-input>
        </el-form-item>
        <el-form-item label="课程所属院系" prop="department">
          <el-input v-model="editForm.department"></el-input>
        </el-form-item>
        <el-form-item label="课程学分" prop="courseCredits">
          <el-input-number v-model="editForm.courseCredits" :min="0" step="0.5"></el-input-number>
        </el-form-item>
        <el-form-item label="课程描述" prop="courseDescription">
          <el-input v-model="editForm.courseDescription"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, computed, onMounted } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";

// 筛选条件
const filterForm = reactive({
  courseId: "",
});

// 表格数据和分页
const courseList = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 查询对话框相关
const queryDialogVisible = ref(false);
const queryCourseInfo = ref({
  courseId: "",
  courseName: "",
  department: "",
  courseCredits: 0,
  courseDescription: "",
});

// 添加课程表单
const addDialogVisible = ref(false);
const addForm = ref({
  courseId: "",
  courseName: "",
  department: "",
  courseCredits: 0,
  courseDescription: "",
});
const addFormRef = ref(null);

// 编辑课程表单
const editDialogVisible = ref(false);
const editForm = ref({
  courseId: "",
  courseName: "",
  department: "",
  courseCredits: 0,
  courseDescription: "",
});
const editFormRef = ref(null);

// 添加表单验证规则
const addFormRules = computed(() => ({
  courseId: [
    { required: true, message: "请输入课程ID", trigger: "blur" },
  ],
  courseName: [
    { required: true, message: "请输入课程名称", trigger: "blur" },
  ],
  department: [
    { required: true, message: "请输入课程所属院系", trigger: "blur" },
  ],
  courseCredits: [
    { required: true, message: "请输入课程学分", trigger: "blur" },
  ],
}));

// 编辑表单验证规则
const editFormRules = computed(() => ({
  courseName: [
    { required: true, message: "请输入课程名称", trigger: "blur" },
  ],
  department: [
    { required: true, message: "请输入课程所属院系", trigger: "blur" },
  ],
  courseCredits: [
    { required: true, message: "请输入课程学分", trigger: "blur" },
  ],
}));

// 生命周期钩子
onMounted(async () => {
  await fetchCourseList();
});

// 获取课程列表
const fetchCourseList = async () => {
  try {
    // const params = {
    //   ...filterForm,
    //   page: currentPage.value,
    //   size: pageSize.value,
    // };
    const formData = new FormData();
    formData.append("classId",filterForm.courseId);
    formData.append("page",currentPage.value);
    formData.append("size",pageSize.value);
    const response = await axios.post("/courses/getCourseList", formData);
    courseList.value = response.data.result || [];
    total.value = response.data.total || 0;
  } catch (error) {
    console.error("获取课程列表失败", error);
    ElMessage.error("获取课程列表失败，请稍后重试");
  }
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.courseId = "";
  fetchCourseList();
};

// 添加对话框关闭时处理
const handleAddDialogClose = () => {
  addDialogVisible.value = false;
};

// 提交添加表单
const submitAddForm = () => {
  addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const formData = new FormData();
        formData.append("courseId", addForm.value.courseId);
        formData.append("courseName", addForm.value.courseName);
        formData.append("department", addForm.value.department);
        formData.append("courseCredits", addForm.value.courseCredits);
        formData.append("courseDescription", addForm.value.courseDescription);

        const response = await axios.post("/courses/addCourse", formData);
        if (response.data.flag) {
          ElMessage.success("课程添加成功");
          addDialogVisible.value = false;
          addForm.value={};
          fetchCourseList();
        } else {
          ElMessage.error(response.data.message || "课程添加失败");
        }
      } catch (error) {
        console.error("添加课程失败", error);
        ElMessage.error("添加课程失败，请稍后重试");
      }
    }
  });
};

// 编辑课程
const handleEdit = (row) => {
  editDialogVisible.value = true;
  editForm.value={...row};
};

// 编辑对话框关闭时处理
const handleEditDialogClose = () => {
  editDialogVisible.value = false;
  editForm.value={};
};

// 提交编辑表单
const submitEditForm = () => {
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const formData = new FormData();
        formData.append("courseId", editForm.value.courseId);
        formData.append("courseName", editForm.value.courseName);
        formData.append("department", editForm.value.department);
        formData.append("courseCredits", editForm.value.courseCredits);
        formData.append("courseDescription", editForm.value.courseDescription);
        const response = await axios.put("/courses/updateCourse", formData);
        if (response.data.flag) {
          ElMessage.success("课程信息更新成功");
          editDialogVisible.value = false;
          fetchCourseList();
        } else {
          ElMessage.error(response.data.message || "课程信息更新失败");
        }
      } catch (error) {
        console.error("更新课程信息失败", error);
        ElMessage.error("更新课程信息失败，请稍后重试");
      }
    }
  });
};

// 删除课程
const handleDelete = (course) => {
  ElMessageBox.confirm(
      `确定要删除课程 "${course.courseName}" (${course.courseId}) 吗？删除后将无法恢复。`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "danger",
      }
  ).then(async () => {
    try {
      const response = await axios.delete(`/courses/deleteCourse?courseId=${course.courseId}`);
      if (response.data.flag) {
        ElMessage.success("课程删除成功");
        fetchCourseList();
      } else {
        ElMessage.error(response.data.message || "课程删除失败");
      }
    } catch (error) {
      console.error("删除课程失败", error);
      ElMessage.error("删除课程失败，请稍后重试");
    }
  }).catch(() => {
    // 取消操作
  });
};

// 双击行编辑
const handleRowClick = (row) => {
  handleEdit(row);
};

// 分页控制
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchCourseList();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchCourseList();
};

// 单独的课程查询方法
const queryCourseDetail = async () => {
  const courseId = filterForm.courseId;

  if (!courseId) {
    ElMessage.warning("请输入课程ID");
    return;
  }

  try {
    const response = await axios.get(`/courses/getCourseDetail?courseId=${courseId}`);
    if (response.data.flag) {
      queryCourseInfo.value = response.data.result;
      queryDialogVisible.value = true;
    } else {
      ElMessage.error(response.data.reason || "查询失败");
    }
  } catch (error) {
    console.error("查询出错:", error);
    ElMessage.error("查询时发生错误，请稍后重试");
  }
};

// 查询对话框关闭时处理
const handleQueryDialogClose = () => {
  queryDialogVisible.value = false;
  queryCourseInfo.value = {
    courseId: "",
    courseName: "",
    department: "",
    courseCredits: 0,
    courseDescription: "",
  };
};
</script>

<style scoped>
.course-management {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.course-list-card {
  height: auto;
  margin-bottom: 20px;
}

.table-container {
  height: 500px;
  overflow-y: auto;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>